import Router from 'koa-router'
import redis from '../../utils/redis.js'

const router = new Router({ prefix: '/message' })

// WebSocket全局或单连接广播（后端转发到 ws.js 订阅通道）
router.post('/broadcast', async (ctx) => {
  const { connId, payload } = ctx.request.body || {}
  if (!payload) {
    ctx.status = 400
    ctx.body = { error: 'payload 必填' }
    return
  }
  await redis.publish('webrtc:broadcast', JSON.stringify({ connId, payload }))
  ctx.body = { success: true }
})

// 指定连接发送（relay）
router.post('/send', async (ctx) => {
  const { connId, payload } = ctx.request.body || {}
  if (!connId || !payload) {
    ctx.status = 400
    ctx.body = { error: 'connId 与 payload 必填' }
    return
  }
  await redis.publish('webrtc:relay', JSON.stringify({ connId, payload }))
  ctx.body = { success: true }
})

export default router


